import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpServer {
    private ServerSocket serverSocket = null;
    public TcpServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器上线!");
        while (true) {
            Socket socket = serverSocket.accept();
            Thread t = new Thread(() ->{
                try {
                    ProcessCollection(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }

    }

    private void ProcessCollection(Socket socket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线!\n",socket.getInetAddress(),socket.getPort());
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            while (true){
                Scanner scanner = new Scanner(inputStream);
                PrintWriter printWriter = new PrintWriter(outputStream);
                if (!scanner.hasNext()){
                    break;
                }
                String request = scanner.next();

                String response = process(request);

                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s:%d] req=%s resp=%s\n",socket.getInetAddress(),socket.getPort(),request,response);
            }
        } catch (IOException e){
            e.printStackTrace();
        }finally {
            System.out.printf("[%s:%d] 客户端下线!\n",socket.getInetAddress(),socket.getPort());
            socket.close();
        }

    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpServer tcpServer = new TcpServer(8888);
        tcpServer.start();
    }
}
